package com.cskaoyan.user.service.impl;

import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.entitys.UserVerify;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dal.persistence.UserVerifyMapper;
import com.cskaoyan.user.form.UserRegisterRequest;
import com.cskaoyan.user.form.UserVerifyRequest;
import com.cskaoyan.user.service.IUserRegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
@Transactional
public class UserRegisterServiceImpl implements IUserRegisterService {

    @Autowired
    MemberMapper memberMapper;

    @Autowired
    UserVerifyMapper verifyMapper;

    // 这个是spring框架自己帮我们封装的邮件发送组件，直接注入即可，不需要我们额外去配置什么
    @Autowired
    MailSender mailSender;

    @Override
    public void register(UserRegisterRequest request) {
        String userName = request.getUserName();
        String userPwd = request.getUserPwd();
        // 把用户的密码加密，狸猫换太子
        userPwd = DigestUtils.md5DigestAsHex(userPwd.getBytes());
        String email = request.getEmail();
        Date now = new Date();
        String key = userName + userPwd + UUID.randomUUID().toString();
        String uuid = DigestUtils.md5DigestAsHex(key.getBytes());

        // 检查邮箱的重复性
        checkMemberRepeat("email", email);

        // 检查用户名的重复性
        checkMemberRepeat("username", userName);

        // 在memeber表里插入基本的信息
        registerInsertIntoMemberTable(userName, userPwd, email, now);

        // verify表里插入数据
        verifyInsert(userName, uuid, now);

        // 发送注册邮件
        sendRegisterEmail(userName, email, uuid);
    }

    private void sendRegisterEmail(String userName, String email, String uuid) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("CSMALL注册激活");
        message.setFrom("764782750@qq.com");
        message.setTo(email);
        StringBuffer sb = new StringBuffer();
        sb.append("http://localhost:8101/user/verify?username=");
        sb.append(userName).append("&uuid=").append(uuid);
        message.setText(sb.toString());
        mailSender.send(message);
    }

    private void checkMemberRepeat(String field, Object checkInfo) {
        Example example = new Example(Member.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo(field, checkInfo);
        List<Member> members = memberMapper.selectByExample(example);

        String info = null;
        if(members.size() != 0){
            if(field.equals("username")){
                info = "用户名";
            }else if(field.equals("email")){
                info = "邮箱";
            }else {
                info = field;
            }
            throw new BizException(UserRetCode.DATA_REPEATED.getCode(), info + "已存在！");
        }
    }

    private void registerInsertIntoMemberTable(String userName, String userPwd, String email, Date now) {
        Member rMember = new Member();
        rMember.setUsername(userName);
        rMember.setPassword(userPwd);
        rMember.setEmail(email);
        rMember.setCreated(now);
        rMember.setUpdated(now);
        rMember.setIsVerified("N");
        int effectRows = memberMapper.insertSelective(rMember);
        // 如果插入出现问题
        if(effectRows == 0){
            throw new BizException(
                    UserRetCode.USER_REGISTER_FAILED.getCode(), UserRetCode.USER_REGISTER_FAILED.getMessage());
        }
    }

    private void verifyInsert(String userName, String uuid, Date now) {
        UserVerify userVerify = new UserVerify();
        userVerify.setUsername(userName);
        userVerify.setIsExpire("N");
        userVerify.setIsVerify("N");
        userVerify.setRegisterDate(now);
        userVerify.setUuid(uuid);
        verifyMapper.insertSelective(userVerify);
    }

    @Override
    public void verify(UserVerifyRequest request) {
        Member member = new Member();
        member.setUsername(request.getUsername());
        Member member1 = memberMapper.selectOne(member);
        // Date createdTime = member1.getCreated();
        // long time = createdTime.getTime();
        // long now = System.currentTimeMillis();
        // long gapTime=now-time;
        // if (gapTime > 300000) {
        //
        // }
        member1.setIsVerified("Y");
        memberMapper.updateByPrimaryKey(member1);
        UserVerify userVerify = new UserVerify();
        userVerify.setUsername(request.getUsername());
        userVerify.setUuid(request.getUuid());
        UserVerify userVerify1 = verifyMapper.selectOne(userVerify);
        userVerify1.setIsVerify("Y");
        userVerify1.setIsExpire("Y");
        verifyMapper.updateByPrimaryKey(userVerify1);
    }
}
